package services;

import org.apache.wicket.authroles.authentication.AuthenticatedWebSession;
import org.apache.wicket.authroles.authorization.strategies.role.Roles;
import org.apache.wicket.injection.Injector;
import org.apache.wicket.request.Request;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

public class HWAuthenticatedSession extends AuthenticatedWebSession 
{
	private static final long serialVersionUID = 1L;
	
    @SpringBean(name = "authenticationManager")
    private AuthenticationManager authenticationManager;

	public HWAuthenticatedSession(Request request) 
	{
        super(request);
        Injector.get().inject(this);
        if (authenticationManager == null) {
            throw new IllegalStateException(
                    " AuthenticationManager injection error");
        }
	}

	@Override
	public boolean authenticate(String username, String password) 
	{
        boolean authenticated = false;
        try {
            Authentication authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(
                            username, password));
            SecurityContextHolder.getContext()
                    .setAuthentication(authentication);
            authenticated = authentication.isAuthenticated();
        } catch (AuthenticationException e) {
            authenticated = false;
        }
        return authenticated;
	}

	@Override
	public Roles getRoles() 
	{
        Roles roles = new Roles();
        if (isSignedIn()) {
            Authentication authentication = SecurityContextHolder.getContext()
                    .getAuthentication();
            for (GrantedAuthority authority : authentication.getAuthorities()) {
                roles.add(authority.getAuthority());
            }
        }
        return roles;
	}

}
